<template>
  <div class="mod-prod-info">
    <el-form
      ref="dataForm"
      :model="dataForm"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item label="产品图片" prop="imgs">
        <mul-pic-upload v-model="dataForm.imgs" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="dataForm.sellStatus">
          <el-radio :label="true">上架</el-radio>
          <el-radio :label="false">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="产品分类"
        prop="categoryId"
      >
        <el-col :span="8">
          <el-cascader
            v-model="category.selected"
            expand-trigger="hover"
            :options="category.list"
            :props="category.props"
            change-on-select
            @change="handleCategoryChange"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="产品分组" prop="groupList">
        <el-col :span="8">
          <el-select
            v-model="dataForm.groupList"
            multiple
            style="width: 250px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in DBGroups"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item
        label="产品名称"
        prop="title"
      >
        <el-col :span="8">
          <el-input
            v-model="dataForm.title"
            placeholder="产品名称"
            maxlength="50"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        label="产品卖点"
        prop="brief"
      >
        <el-col :span="8">
          <el-input
            v-model="dataForm.brief"
            type="textarea"
            :autosize="{minRows: 2, maxRows: 4}"
            placeholder="产品卖点"
          />
        </el-col>
      </el-form-item>
      <!--      <el-form-item label="配送方式">-->
      <!--        <el-checkbox v-model="dataForm.deliveryMode.hasShopDelivery">商家配送</el-checkbox>-->
      <!--        <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp">用户自提</el-checkbox>-->
      <!--      </el-form-item>-->
      <sku-tag
        ref="skuTag"
        :skuTags="skuTags"
        :propList="propList"
        @addTag="addSkuProp(arguments)"
        @addPropValue="addPropValue(arguments)"
        @handleTagClose="handleTagClose(arguments)"
        @removeTag="removeTag(arguments)"
      />
      <sku-table
        ref="skuTable"
        v-model="dataForm.skuList"
        :skuTags="skuTags"
      />

      <el-form-item
        label="产品详情"
        prop="details"
      >
        <tiny-mce
          ref="details"
          v-model="dataForm.details"
          :tinymce-height="tinymceHeight"
          style="width:1000px"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import MulPicUpload from '@/components/mul-pic-upload'
import SkuTag from './sku-tag'
import SkuTable from './sku-table'
import TinyMce from '@/components/tiny-mce'
import { getTree } from '@/api/mall/category'
import { listTagList } from '@/api/mall/prodGroup'
import { saveProduct,getProductDetail } from '@/api/mall/product'
import { getPropList } from '@/api/mall/prodProp'

export default {
  components: {
    MulPicUpload,
    TinyMce,
    SkuTag,
    SkuTable
  },
  data() {
    return {
      tinymceHeight: 800,
      // 分类树展示与回显
      category: {
        list: [],
        selected: [],
        props: {
          value: 'id',
          label: 'name'
        }
      },
      // 规格列表
      dataForm: {
        title: '',
        brief: '',
        pic: '',
        imgs: [],
        categoryId: 0,
        prodId: 0,
        skuList: [],
        groupList: [],
        status: 1,
        details: ''
        // deliveryMode: {
        //   hasShopDelivery: false,
        //   hasUserPickUp: false
        // },
        // deliveryTemplateId: null
      },
      rules: {
        imgs: [
          { type: 'array', required: true, message: '请选择图片上传', trigger: 'change' }
        ],
        title: [
          { required: true, message: '产品名称不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { type: 'number', required: true, min: 1, message: '请选择商品分类', trigger: 'change' }
        ],
        groupList: [
          { type: 'array', required: true, message: '请选择商品分组', trigger: 'change' }
        ]
      },
      DBGroups: [], //系统里已有分组列表
      skuTags:[], //当前商品用到的属性列表
      propList:[],//系统里已有的属性列表
      //      resourcesUrl: window.SITE_CONFIG.resourcesUrl
    }
  },
    props:{
        prod_id:{
            default:0,
            type: Number
        }
    },
  computed: {
    defalutSku() {
      return this.$store.state.prod.defalutSku
    }
  },
  created() {
    this.dataForm.prodId = this.$route.query.prodId
    this.getDataList()
  },
  methods: {
    removeEmptyChildren(list) {
      const _this = this
      list.forEach(function(item, index) {
        if (item.children.length > 0) {
          _this.removeEmptyChildren(item.children)
        } else {
          item.children = undefined
        }
      })
    },
    getAttrData(){
        const _this = this
        const loading = _this.$loading({
            lock: true,
            text: '请稍后...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        })
        getPropList().then(res=>{
            this.propList=res
            if(_this.prod_id){ //如果是编辑商品 先获取商品详情
                getProductDetail(_this.prod_id).then(res=>{
                    _this.dataForm=res
                    //初始化商品分类
                    for(const i in _this.category.list){
                        const ca=_this.category.list[i]
                        if(ca.id===res.categoryId){
                            _this.category.selected.push(res.categoryId)
                        }else{
                            for(const j in ca.children){
                                const ca_c=ca.children[j]
                                if(ca_c.id===res.categoryId){
                                    const selectedValue=[]
                                    selectedValue.push(ca.id)
                                    selectedValue.push(res.categoryId)
                                    _this.category.selected=selectedValue
                                    break
                                }
                            }
                        }
                    }
                    //初始化商品属性
                    res.skuList.forEach(sku=>{
                        sku.properties.forEach(prop=>{
                            _this.propList.forEach(attr=>{
                                if(attr.name === prop.name){
                                    let attr_tmp
                                    const skuTagsTmp=_this.skuTags
                                    skuTagsTmp.forEach(sku_tag=>{
                                        if(sku_tag.name === prop.name){
                                            attr_tmp=sku_tag
                                        }
                                    })
                                    if(!attr_tmp){
                                        attr_tmp=JSON.parse(JSON.stringify(attr))
                                        delete attr_tmp.valueList
                                        attr_tmp.selectValues=[]
                                        skuTagsTmp.push(attr_tmp)
                                    }
                                    attr_tmp.selectValues.push(prop.value)
                                    _this.skuTags=skuTagsTmp
                                }
                            })
                        })
                    })
                    loading.close()
                }).catch(()=>{
                    loading.close()
                })
            }else{
                loading.close()
            }
        }).catch(()=>{
            loading.close()
        })
    },
    // 获取分类数据
    getDataList() {
      const _this = this
      const loading = _this.$loading({
            lock: true,
            text: '请稍后...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
      })
      listTagList().then(res => {
        _this.DBGroups = res
          getTree().then(res => {
              loading.close()
              _this.removeEmptyChildren(res)
              _this.category.list = res
              _this.getAttrData()
          }).catch(()=>{
              loading.close()
          })
      }).catch(()=>{
          loading.close()
      })

    },
    // 选择分类改变事件
    handleCategoryChange(val) {
        console.log(this.category)
      this.dataForm.categoryId = val[val.length - 1]
    },
    // 表单提交
    dataFormSubmit() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return
        }
        if (this.dataForm.imgs.length === 0) {
          this.errorMsg('请选择图片上传')
          return
        } else if (this.dataForm.categoryId === 0) {
          this.errorMsg('请选择商品所属分类')
          return
        }
        // if (!this.dataForm.deliveryMode) {
        //   this.errorMsg('请选择配送方式')
        //   return
        // }
        // if (this.dataForm.deliveryMode.hasShopDelivery && !this.dataForm.deliveryTemplateId) {
        //   this.errorMsg('请选择运费模板')
        //   return
        // }
          const param = Object.assign({}, this.dataForm)
          this.paramSetPriceAndStocks(param)
          console.log(param.skuList)
          for(const i in param.skuList){
              const sku = param.skuList[i]
              if(!sku.pic){
                  this.errorMsg('请上传SKU图片')
                  return
              }
          }
          const loading = _this.$loading({
              lock: true,
              text: '请稍后...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
          })
        // 设置价格和库存
        // param.deliveryMode = undefined
        // param.deliveryModeVo = undefined
        // // 商品主图
        // param.pic = this.dataForm.imgs[0]
        console.log(param)
          saveProduct(param).then(res=>{
              loading.close()
              _this.$parent.saveProductCallback();
             console.log(res)
          }).catch(()=>{
              loading.close()
          })
      })
    },
    paramSetPriceAndStocks(param) {
      // 获取规格属性信息
      // param.skuList = this.$refs.prodSpec.getTableSpecData()
      // 商品库存
      param.totalStocks = 0
      // 商品价格
      param.price = 0
      // 商品原价
      param.oriPrice = 0
      // 商品实际库存
      for (let i = 0; i < param.skuList.length; i++) {
        const element = param.skuList[i]
        if (element.status !== 1) {
          continue
        }
        if (param.price === 0) {
          param.price = element.price ? Number.parseFloat(element.price) : 0
        }
        // 商品价格为最低价的那件商品的价格
        param.price = Math.min(param.price, element.price)
        if (param.price === element.price) {
          param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
        }
        param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
      }
      // 如果sku没有商品名称，则使用商品的商品名称
      if (param.skuList.length === 1) {
        param.skuList[0].prodName = this.dataForm.prodName
      }
    },
    addSkuProp(args){
        const prop = args[0];
        const skuList = this.dataForm.skuList
        if(skuList.length==0){
            prop.selectValues.forEach(value => {
                const sku_temp={
                    price: 0, // 销售价
                    oriPrice: 0, // 市场价
                    stocks: 0, // 库存
                    properties: [{name:prop.name,value}], // 销售参数组合,JSONArray格式[{name:'产地',value:'丹麦'}]
                    skuName: '', // sku名称
                    prodName: '', // 商品名称
                    weight: 0, // 商品重量
                    volume: 0, // 商品体积
                    status: 1 // 0 禁用 1 启用
                }
                skuList.push(sku_temp)
            })
        }else{
            this.dataForm.skuList.forEach(sku => {
                const sku_temp= JSON.parse(JSON.stringify(sku))
                const properties = sku.properties
                properties.push({name:prop.name,value:prop.selectValues[0]})
                if(prop.selectValues.length>1){
                    for(let i=1;i<prop.selectValues.length;i++){
                        sku_temp.properties.push({name:prop.name,value:prop.selectValues[i]})
                        skuList.push(sku_temp)
                    }
                }
            })
        }
        this.dataForm.skuList = skuList
        this.skuTags.push(prop)
    },
    addPropValue(args){
        const index = args[0]
        const value = args[1]
        for(let i=0;i<this.skuTags[index].selectValues.length;i++){
         if(this.skuTags[index].selectValues[i] === value){
             this.errorMsg('已经含有相同的属性值【'+value+'】')
             return
         }
        }
        this.skuTags[index].selectValues.push(value)
        const sku_temp={
            price: 0, // 销售价
            oriPrice: 0, // 市场价
            stocks: 0, // 库存
            properties: [
                {
                    name:this.skuTags[index].name,
                    value
                }
            ], // 销售参数组合,JSONArray格式[{name:'产地',value:'丹麦'}]
            skuName: '', // sku名称
            prodName: '', // 商品名称
            weight: 0, // 商品重量
            volume: 0, // 商品体积
            status: 1 // 0 禁用 1 启用
        }
        if(this.skuTags.length===1){ //只有当前一个属性
            this.dataForm.skuList.push(sku_temp)
        }else{ //还有其他属性
            const skuTagsTmp=JSON.parse(JSON.stringify(this.skuTags))
            for(let i=0;i<skuTagsTmp.length;i++){
                if(skuTagsTmp[i].name === this.skuTags[index].name){
                    skuTagsTmp.splice(i,1)
                    break
                }
            }
            const valueTmp={name:this.skuTags[index].name,value}
            let arr = [];        // 初始化第一个内层数组
            const firstArray=[]
            firstArray.push(valueTmp)
            arr.push(firstArray)
            /**
             * 遍历外层数组
             */
            for (let i = 0; i < skuTagsTmp.length; i++) {
                // console.log('外层数组索引 = ' + index);
                arr = this.getValuesByArray(arr, skuTagsTmp[i]);
            }
            arr.forEach(propItem=>{
                const sku_temp_temp={...sku_temp}
                sku_temp_temp.properties=propItem
                this.dataForm.skuList.push(sku_temp_temp)
            })
            // console.log(arr.length)
        }
    },
    getValuesByArray(arr1, attr2){
          var arr = [];
          const arr2=attr2.selectValues

          /**
           * 遍历外层数组
           */
          for (var index = 0; index < arr1.length; index++) {
              const firstArray = arr1[index];

              /**
               * 遍历内层数组
               */
              for(var cursor = 0; cursor < arr2.length; cursor++) {
                  var value2 = {name:attr2.name,value:arr2[cursor]};

                  const value = []
                  firstArray.forEach(array=>{
                      value.push(array)
                  })
                  value.push(value2)
                  // const value = value1 + ' - ' + value2;

                  arr.push(value);
                  // console.log(arr);
              };
          };

          return arr;

    },
    handleTagClose(args) {
      const tagIndex=args[0]
      const tagItemIndex=args[1]
      const attr=this.skuTags[tagIndex]
      const attr_value=this.skuTags[tagIndex].selectValues[tagItemIndex]
      const skuList=this.dataForm.skuList
      const newList=skuList.filter(item=>{
        for(let i=0;i<item.properties.length;i++){
            if(item.properties[i].name===attr.name&&attr_value ===item.properties[i].value){
                return false //删除符合条件的
            }
        }
        return true
      })
      this.skuTags[tagIndex].selectValues.splice(tagItemIndex, 1)
      this.dataForm.skuList=newList
    },
    removeTag(args){//删除属性
      const tagIndex=args[0]
      const attr=this.skuTags[tagIndex]
      this.dataForm.skuList.forEach(sku=>{
          for(let i=0;i<sku.properties.length;i++){
              if(sku.properties[i].name===attr.name){
                  sku.properties.splice(i, 1)
                  break
              }
          }
      })
      this.skuTags.splice(tagIndex, 1)
      if(this.skuTags.length==0){ //属性删除完了 也就没有SKU了
          this.dataForm.skuList=[]
      }else{
          const propList=[]
          this.dataForm.skuList=this.dataForm.skuList.filter(item=>{
              if(!this.propListContain(propList,item.properties)){
                  propList.push(item.properties)
                  return true
              }else{
                  return false
              }
          })
      }
    },
    propListContain(propList,properties){
        L1:
        for(let item of propList){
          let contain=[]
          L2:
          for(let prop_item of properties){
              const name=prop_item.name
              const value=prop_item.value
              for(let i_item of item){
                  if(name === i_item.name&& value===i_item.value){
                      contain.push(true)
                      continue L2
                  }
              }
                contain.push(false)
          }
          for(let c_contain of contain){
              if(!c_contain){
                  continue L1
              }
          }
          return true
        }
        return false
    },
    errorMsg(message) {
      this.$message({
        message: message,
        type: 'error',
        duration: 1500
      })
    }
  }
}
</script>
